package cn.ray.springframework.beans.factory.support;

import cn.ray.springframework.beans.BeansException;
import cn.ray.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;


//使用反射来创建 即Java本身自带的DeclaredConstructor方法
public class SimpleInstantiateStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        Class clazz=beanDefinition.getBeanClass();
        try{
            if(ctor!=null){
                //不为空则是有构造函数的实例化
                //把入参信息传递给newInstance实例化
                //ctor.getParameterTypes()-->{String.class}
                //clazz.getDeclaredConstructor根据参数列表找对应构造函数
                //等同于UserService userService=new UserService(”张三")
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            }
            else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        }catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }
}
